import { fetchStore } from '../../services/store/store';

import { getResolutionRatio } from '../../utils/resolution';

const { doLogin, checkLogin } = require('../../utils/common');

const { createBooking } = require('../../services/order/prebook');

let bannerRatio = getResolutionRatio('banner', 0);
let innerBannerRatio = getResolutionRatio('banner', 70);

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperHeight: bannerRatio.height,
    innerBannerHeight: innerBannerRatio.height,
    id: 0,
    title: '曼格纳·漫芯馆(浦江镇)',
    business_hours: '09:00 - 22:00',
    tags: ['大型会务', '婚宴/宝宝宴', '商务宴请'],
    address: '闵行区竹园路559号7号楼',
    distance: '距离您2.4公里 驾车10分钟 步行25分钟',
    coordinate: {
      latitude: 0,
      longitude: 0,
    },
    mobile: '',
    menus: [],
    halls: [],
    activeBussiness: 'wedding',
    activeMenu: '',
    currentHall: {
      id: 0,
      title: '',
      titlepic: '',
      tables: '',
      height: '',
      area: '',
      shape: '',
      pillar: '',
      album: [],
    },
    days: [],
    activeDay: '',
    peoples: [
      {
        value: '1-4人',
        label: '1-4人'
      },
      {
        value: '4-8人',
        label: '4-8人'
      },
      {
        value: '8-12人',
        label: '8-12人'
      },
      {
        value: '12-20人',
        label: '12-20人'
      },
      {
        value: '20人以上',
        label: '20人以上'
      },
    ],
    activePeople: '1-4人',
    roomTypes: [
      {
        value: "pubic",
        label: '大厅',
        desc: '1-4人可订'
      },
      {
        value: "vip",
        label: 'VIP包房',
        desc: '10人以上可订'
      },
    ],
    activeRoomType: 'pubic',
    // 表单数据
    formData: {
      name: '',
      gender: '1', // 1 先生, 0 女士
      phone: '',
      remark: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options);
    let days = this._generateDays(20)
    this.setData({
      id: options.id,
      days: days,
      activeDay: days[0].value,
    });

    this.fetchStoreData(options.id)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.fetchStoreData(this.data.id)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  fetchStoreData(id, type) {
    let m = {
      id: 0,
      title: '',
      titlepic: '',
      tables: '',
      height: '',
      area: '',
      shape: '',
      pillar: '',
      album: []
    };

    fetchStore(id).then(({ store, halls, menus }) => {
      // 解析坐标
      const [longitude, latitude] = store.coordinate.split(',');
      this.setData({
        title: store.title,
        business_hours: store.business_hours,
        coordinate: { latitude: Number(latitude), longitude: Number(longitude) },
        mobile: store.mobile,
        tags: store.tags,
        address: store.address,
        album: store.album,
        halls: halls,
        menus: menus,
        currentHall: halls.length > 0 ? halls[0] : m,
      });
    })
  },

  tapBusinessNav(e) {
    this.setData({
      activeBussiness: e.target.dataset.type,
    });
  },

  goBack() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  },

  // 生成从今天起 n 天的数组，包含 date(YYYY-MM-DD)、display、weekday、label、isToday
  _generateDays(n = 20) {
    const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const res = [];
    const today = new Date();
    for (let i = 0; i < n; i++) {
      const d = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
      const yyyy = d.getFullYear();
      const mm = String(d.getMonth() + 1).padStart(2, '0');
      const dd = String(d.getDate()).padStart(2, '0');
      const date = `${yyyy}-${mm}-${dd}`;
      const display = `${mm}/${dd}`;
      const weekday = week[d.getDay()];
      const isToday = i === 0;
      const label = i === 0 ? '今天' : i === 1 ? '明天' : weekday;
      res.push({ value: date, display, weekday, label, isToday });
    }
    return res;
  },

  tapDay(e) {
    console.log(e);
    this.setData({
      activeDay: e.currentTarget.dataset.value,
    });
  },

  tapPeople(e) {
    console.log(e);
    this.setData({
      activePeople: e.currentTarget.dataset.value,
    });
  },

  tapRoomType(e) {
    console.log(e);
    this.setData({
      activeRoomType: e.currentTarget.dataset.value,
    });
  },

  tapGender(e) {
    console.log(e);
    this.setData({
      activeGender: e.currentTarget.dataset.value,
    });
  },

  toggleHall(e) {
    console.log(e);
    const { id } = e.currentTarget.dataset;
    this.setData({
      currentHall: this.data.halls.find(hall => hall.id == id),
    });
  },

  // 打车
  tapCallCar(e) {
    const { latitude, longitude } = this.data.coordinate;
    const { title, address } = this.data;
    wx.openLocation({
      latitude,
      longitude,
      name: title,
      address,
    })
  },

  // 打电话
  tapCallPhone(e) {
    const { mobile } = this.data;
    wx.makePhoneCall({
      phoneNumber: mobile,
    })
  },

  // 查看详情
  tapViewDetail(e) {
    // 检查是否已登录
    if (checkLogin()) {
      // 已登录，直接跳转
      const { id, type } = e.currentTarget.dataset;
      let sid = this.data.id;
      wx.navigateTo({
        url: `/pages/hall/detail?id=${id}&type=${type}&sid=${sid}`,
      });
    } else {
      // 未登录，先登录再跳转
      doLogin()
        .then(() => {
          // 登录成功后跳转
          const { id, type } = e.currentTarget.dataset;
          let sid = this.data.id;
          wx.navigateTo({
            url: `/pages/hall/detail?id=${id}&type=${type}&sid=${sid}`,
          });
        })
        .catch(err => {
          console.error('登录失败，无法查看详情', err);
          wx.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        });
    }
  },

  // 性别选择
  tapGender(e) {
    this.setData({
      'formData.gender': e.detail.value
    });
  },

  // 输入框内容变化
  onInputChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 提交预定表单
  submitBooking() {
    // 检查登录状态
    if (!checkLogin()) {
      doLogin()
        .then(() => {
          this.submitBookingRequest();
        })
        .catch(err => {
          console.error('登录失败', err);
          wx.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        });
    } else {
      this.submitBookingRequest();
    }
  },

  // 提交预定请求
  submitBookingRequest() {
    const { formData, activeDay, activePeople, activeRoomType, id } = this.data;
    
    // 表单验证
    if (!formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    if (!formData.phone.trim()) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return;
    }

    // 构建提交数据
    const submitData = {
      store_id: id,
      use_date: activeDay,
      people: activePeople,
      room_type: activeRoomType,
      name: formData.name,
      gender: formData.gender,
      phone: formData.phone,
      remark: formData.remark,
      openid: wx.getStorageSync('openid')
    };

    wx.showLoading({
      title: '提交中...'
    });

    // 使用预定服务
    createBooking(submitData)
      .then((res) => {
        wx.hideLoading();
        wx.showToast({
          title: '预定成功',
          icon: 'success'
        });
        
        // 清空表单
        this.setData({
          'formData.name': '',
          'formData.phone': '',
          'formData.remark': '',
          'formData.gender': '1'
        });
        
        // 延迟跳转到预定列表页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/booking/list'
          });
        }, 1500);
      })
      .catch((err) => {
        wx.hideLoading();
        console.error('预定请求失败', err);
        wx.showToast({
          title: err.message || '预定失败',
          icon: 'none'
        });
      });
  },
})